import logging
from logging import debug
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

from header_reading import read_head, save_describ, estimate_para_type_from_data
from read_raw_data import read_csv_file

from prepare_for_save import prepare_data
from prepare_for_save import add_turbid
from write_to_h5 import write_to_h5

# GTK imports
import pygtk
pygtk.require("2.0")
import gtk
import gobject

gobject.threads_init()
# Initialize GTK threads
class client():

    def __init__(self):
        # Build GTK from glade files
        builder = gtk.Builder()
        builder.add_from_file("../glade_files/csv_wind.glade")

        # Get GTK objects from glade file
        self.w = builder.get_object("mainwindow")

        # Reading in all the objects from gtk and create self.object to each from the glade object file
        obs = builder.get_objects()
        for ob in obs:
            try:
                ob_name = gtk.Buildable.get_name(ob)
                exe_string = "self." + ob_name + " = builder.get_object(\"" + ob_name + "\")"
                exec(exe_string)
            except:
                pass

        # Class variables
        self.delim = ","
        self.para_describ = []
        self.para_names = []
        self.turbine = ""
        self.folder_selected = False

        # Connecting all signals and start main window
        builder.connect_signals(self)
        self.w.show_all()

        # Start the GTK main thread
        gtk.main()
    #
    # Signal handlers
    #
    def csv_file_chooser_file_set_cb(self, button):
        self.folder_selected = False
        debug("new file selected")
        self._set_statusbar("New csv file selected")
        csv_file = self.csv_file_chooser.get_filename()
        self.csv_files = [csv_file,]
        debug(self.csv_files)


    def csv_folder_chooser_file_set_cb(self, button):
        import glob
        self.folder_selected = True
        debug("Folder selected")
        folder = self.csv_folder_chooser.get_filename()
        csv_files = glob.glob1(folder, "*.csv")
        self._set_statusbar("Folder with " + str(len(csv_files)) + " csv file(s) selected")
        self.csv_files = [ folder + '/' + csv_file for csv_file in csv_files ]


    def read_header_clicked_cb(self, button):
        self.read_header()

    def read_header(self):
        debug("Reading header")
        self.turbines = []
        for csv_file in self.csv_files:
            turb, cl_names, para_types, deli = read_head(csv_file)
            self.turbines.append(turb)
        self.delim = deli
        self._update_para_table(cl_names, para_types)
        years = [int(i) for i in self.time_entry_year_pos.get_text().split(":")]
        months = [int(i) for i in self.time_entry_month_pos.get_text().split(":")]
        day = [int(i) for i in self.time_entry_day_pos.get_text().split(":")]
        hour = [int(i) for i in self.time_entry_hour_pos.get_text().split(":")]
        minute = [int(i) for i in self.time_entry_min_pos.get_text().split(":")]
        second = [int(i) for i in self.time_entry_sec_pos.get_text().split(":")]
        micro_second = [int(i) for i in self.time_entry_microsec_pos.get_text().split(":")]
        time_format = years, months, day, hour, minute, second, micro_second
        self.time_format = time_format
        debug(turb)
        debug(time_format)


    def read_data_clicked_cb(self, button):
        self.read_data()


    def read_data(self):
        self.data_sets = []
        para_names = self.para_names
        para_describs = self._get_describs(self.para_describ)
        delim = self.delim
        debug("Reading data from file")
        for i, filename in enumerate(self.csv_files):
            debug(filename)
            data = read_csv_file(filename, para_names, para_describs, delim, self.time_format)
            self.data_sets.append(data)
        debug("Data loaded")
        self._set_statusbar("Data loaded")


    def filter_data_clicked_cb(self, button):
        self.filter_data()


    def filter_data(self):
        debug("Filtering the data")
        para_describs = self._get_describs(self.para_describ)
        new_data_sets = []
        for data, turbine in zip(self.data_sets, self.turbines):
            new_data = prepare_data(data, para_describs)
            new_data = add_turbid(new_data, turbine)
            new_data_sets.append(new_data)
        names, para_types = estimate_para_type_from_data(new_data)
        self._update_para_table(names, para_types)
        self.data_sets = new_data_sets
        self._set_statusbar("Data filtered")


    def save_parameters_clicked_cb(self, button):
        self.save_parametes()


    def save_parametes(self):
        debug("Saving parameters")
        describs = self._get_describs(self.para_describ)
        save_describ(self.para_names, describs)


    def save_data_clicked_cb(self, button):
        self.save_data()


    def save_data(self):
        folder = self.output_folder_chooser.get_filename()
        file_name = self.output_file.get_text()
        f_path = folder + "/" + file_name
        debug("Saving data to")
        debug(f_path)
        for data_set in self.data_sets:
            write_to_h5(data_set, f_path)
        debug("Data saved")


    def do_checks_clicked_cb(self, button):
        self.do_checks()


    def do_checks(self):
        if self.read_head_check.get_active():
            self.read_header()
        if self.read_data_check.get_active():
            self.read_data()
        if self.filter_data_check.get_active():
            self.filter_data()
        if self.save_parameters_check.get_active():
            self.save_parametes()
        if self.save_data_check.get_active():
            self.save_data()

    # Quit buttons
    def mainwindow_destroy_cb(self, event):
        self.quit()


    def quit_activate_cb(self, event):
        self.quit()


    def quit(self):
        gtk.main_quit()


    # Helper functions
    def _set_statusbar(self, text):
        self.statusbar.push(1, text)


    def _update_para_table(self, cl_names, para_types):
        self.para_describ = []
        self.names = []
        self.para_names = cl_names

        # Clear table before adding new content to it
        children = self.parameter_table.get_children()
        for child in children:
            self.parameter_table.remove(child)

        self.parameter_table.resize((len(cl_names)), 3)

        for i, name in enumerate(cl_names):
            child = gtk.Label(name)
            child.set_alignment(0, 0.5)
            text = gtk.Entry(50)
            text.set_text(para_types[i])
            self.para_describ.append(text)
            self.parameter_table.attach(child, 0, 1, i, i + 1)
            self.parameter_table.attach(text, 1, 2, i, i + 1)
        self.w.show_all()


    def _get_describs(self, para_describs):
        """ Convert entry text to text list"""
        describ_list = []
        for para in para_describs:
            describ_list.append(para.get_text())
        return describ_list


if __name__ == "__main__":
    # Start the client
    client()
